<?php
require_once 'application/libraries/openid.php';
require_once 'application/helpers/HashGenerator.php';

class Login extends AsbtractRestController {

	public function __construct() {
		parent::__construct();
	}
	
	public function google_get() {
			try {
				$openid = new LightOpenID('localhost');
				$openid->required = array(
						'namePerson',
						'namePerson/first',
						'namePerson/last',
						'contact/email',
				);
				$this->session->set_userdata(array('auth' => 'Google'));
				$openid->identity = 'https://www.google.com/accounts/o8/id';
				$openid->returnUrl = site_url("Validate/google");
				header('Location: ' . $openid->authUrl());
			} catch(ErrorException $e) {
				return $this->constructErrorMsg(ErrorMessgaes::$USER_AUTH_GOOGLE_CODE, ErrorMessgaes::$USER_AUTH_FAILED_MSG);
			}
	}
	
	public function user_post() {
		$this->load->helper('form');
		$this->load->library('form_validation');
		$user = $this->input->post("email");
		$password = $this->input->post("password");
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('password', 'Password', 'required|min_length[5]|max_length[12]');
		if ($this->form_validation->run() == FALSE) {
			return $this->response($this->constructErrorMsg(ErrorMessgaes::$USER_AUTH_CODE, validation_errors()));
		}
		$arr_resp = $this->storeData($user,$password);
		if (isset($arr_resp)) {
			return $this->response($arr_resp);
		}
	}
	

	private function storeData($email,$password) {
		$this->session->set_userdata(array("email" => $email));
		$user = $this->load->model("User");
		$error_msg = $this->User->insertUser($email,HashGenerator::hashClearPassword($password),'Self');
		if (isset($error_msg)) {
			return $this->constructErrorMsg(ErrorMessgaes::$USER_AUTH_CODE,$error_msg);
		}
	}

}
